<template>
  <div class="dictionaryData h100">
    <div class="PageContent">
        <el-col :span="4" class="left-tree">
          <el-tree :data="treeData" ref="dictTree"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="handleCheck"
          ></el-tree>
        </el-col>
        <el-col :span="20"  class="right-tree">
          <el-row style="text-align: left;line-height: 5em;">
            <el-button type="primary" plain v-if="btnRight.btnDictionaryDataAdd" @click="add()" >添加</el-button>
            <el-button type="primary"  v-if="btnRight.btnDictionaryDataEdit"  @click="modifyItem()">修改</el-button>
            <el-button type="danger"   v-if="btnRight.btnDictionaryDataDelete"  @click="deleteItem()">删除</el-button>
          </el-row>
          <el-table
            ref="singleDictionTable"
            :data="dictionaryTableData" :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
            border
            stripe
            @row-click="handleRowClick"
            @select="select" @select-all="selectAll"
            :default-sort = "{prop: 'dataCode', order: 'ascending'}"
            style="width: 100%;height: calc(100% - 80px);overflow-y: scroll">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <!--<el-table-column-->
              <!--property="dictCode"-->
              <!--label="字典编码"-->
              <!--align = 'center'-->
              <!--width="200">-->
            <!--</el-table-column>-->
            <el-table-column
              property="dataCode"
              label="数据编码"
              align = 'center'
              width="200">
            </el-table-column>
            <el-table-column
              property="dataText"
              label="显示文本"
              align = 'center'
              width="200">
            </el-table-column>
            <el-table-column
              property="dataTextAbbr"
              align = 'center'
              label="拼音缩写"
              width="200">
            </el-table-column>
            <el-table-column
              property="asDefault"
              align = 'center'
              label="默认值"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.asDefault==0">非默认</span>
                <span v-else-if="row.asDefault==1">默认</span>
              </template>
            </el-table-column>
            <el-table-column
              property="disableState"
              align = 'center'
              label="禁用状态"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.disableState==0">有效</span>
                <span v-else-if="row.disableState==1">无效</span>
              </template>
            </el-table-column>
            <el-table-column
              property="unmodified"
              align = 'center'
              label="维护状态(仅显示)">
              <template slot-scope="{row,$index}">
                <span v-if="row.unmodified==0">可维护</span>
                <span v-else-if="row.unmodified==1">不可维护</span>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px">
          </div>

        </el-col>
    </div>
    <el-dialog title="数据字典维护" :visible.sync="dialogVisibleType" width="40%" v-dialogDrag   border  @close="closeDialog()">
      <el-form :model="saveDictionary" :rules="rules" ref="dicdialog" :inline="true" label-width="120px" :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="字典名称:" >
            <span>{{saveDictionary.dataDescribe}}</span>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="数据编码:" prop="dataCode">
            <el-input v-model="saveDictionary.dataCode"  @input="change(saveDictionary.dataCode)" :disabled="modifyFlag" maxlength="50"></el-input>
          </el-form-item>
          <el-form-item label="显示文本:" prop="dataText">
            <el-input v-model="saveDictionary.dataText"  :maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <!--<el-row :gutter="5">-->
        <!--<el-form-item label="拼音缩写:" >-->
        <!--<el-input v-model="saveDictionary.dataTextAbbr" :maxlength="20"></el-input>-->
        <!--</el-form-item>-->
        <!--</el-row>-->
        <el-row :gutter="5">
          <el-form-item label="是否默认值:" prop="asDefault" >
            <!--<el-radio-group v-model="saveDictionary.asDefault">-->
            <!--<el-radio :label="1">默认值</el-radio>-->
            <!--<el-radio :label="0" selected>非默认值</el-radio>-->
            <!--</el-radio-group>-->
            <el-select v-model="saveDictionary.asDefault" style="width: 185px;" placeholder="请选择" >
              <el-option
                v-for="item in defaultValue"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="禁用状态:" prop="disableState" >
            <!--<el-radio-group v-model="saveDictionary.disableState">-->
            <!--<el-radio :label="1">无效禁用</el-radio>-->
            <!--<el-radio :label="0" selected>有效可用</el-radio>-->
            <!--</el-radio-group>-->
            <el-select v-model="saveDictionary.disableState" onkeydown="return (event.keyCode!=8)" style="width: 185px;" placeholder="请选择" >
              <el-option
                v-for="item in disableState"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>

        <el-row :gutter="5">
          <el-form-item label="排序:"  >
            <el-input onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"  v-model="saveDictionary.sort" @mousewheel.native.prevent :maxlength="20"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注:"  >
            <el-input  type="textarea" v-model="saveDictionary.remark" style="width: 502px;"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary"  v-if="btnRight.btnDictionaryDataSave"  @click="submit()" :disabled="saveFlag">保存</el-button>
        <el-button type="primary" plain v-if="btnRight.btnDictionaryDataCancel"   @click="cancelForm()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import * as API from '@/api/systemApplication'
  import {treeDictionaryformate} from "../../utils/treeDictionaryformate";
  export default {
    name: "dictionaryData",
    data(){
      return{
        rules: {
          dataCode: [{required: true, message: '请输入数据编码', trigger: 'blur'}],
          dataText: [{required: true, message: '请输入显示文本', trigger: 'blur'}],
          asDefault: [{required: true, message: '请选择默认值', trigger: 'blur'}],
          disableState: [{required: true, message: '请选择禁用状态', trigger: 'blur'}],
        },
        treeData: [{
          label: '系统字典',
          children: []
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        dictionaryTableData: [{
          "id": 0,
          "serviceTypeId": 0,
          "serviceTypeName": "string",
          "itemCode": "string",
          "itemName": "string",
          "itemPrice": 0,
          "itemNumber": 0,
          "itemUnit": "string",
          "asGoods": 0,
          "asPackage": 0,
          "asFixPrice": 0,
          "disableState": 0,
          "itemDescribe": "string",
          "sort": 0,
          "remark": "string",
          "version": 0
        }],
        currentRow: null,
        tableSelection:[],
        selectOrg: {
          orgsid: []
        },
        saveFlag:false, //保存标志
        onpresscTime:0,
        dialogVisibleType:false,  //项目分类维护对话框
        saveDictionary:{       //保存字典信息
          "id": 0,
          "deleted":0,//删除标记
          "dictCode":"",//字典编码
          "dataCode": "",//数据编码
          "dataText": "",//数据文本值
          "dataTextAbbr": "",//数据文本值拼音缩写
          "dataValue": "",//数据数字值
          "dataDescribe": "",//数据扩展描述
          "sort": 0,//排序
          "remark": "",//备注
          "asDefault":0,//默认值
          "disableState":0,//禁用值
          "version": 0,//版本
          "funeralParlourCode": 0,//殡仪馆代码
        },
        defaultValue:[
          { label:'默认值',value:1 },
          { label:'非默认值',value:0 }],
        disableState:[
          { label:'有效',value:0 },
          { label:'无效',value:1}],
        btnRight: {
          btnDictionaryDataAdd: true, //字典明细新增
          btnDictionaryDataEdit: true,//字典明细修改
          btnDictionaryDataDelete: true,//字典明细删除
          btnDictionaryDataSave: true,//字典明细保存
          btnDictionaryDataCancel: true,//字典明细取消
        },
        modifyFlag:false,//修改标志
      }
    },
    mounted(){
      //载入选中字典类型
      this.loadDictionaryList()
      //载入按钮
      this.btnRight = this.$route.meta.buttons;//mounted(){}
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //字典基本信息
      loadDictionaryList(){
        //debugger;
        let postData={
        }
        API['loadDictionaryList'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          this.treeData = treeDictionaryformate(data)
        }).catch(error => {
          this.$message(error)
        })
      },
      change(val){
        val = val.replace(/(^\s*)|(\s*$)/g, "")
        if(!val) {
          this.saveDictionary.dataCode= "";
          return
        }
        let reg = /[^\d]/g
        // 只能是数字和小数点，不能是其他输入
        val = val.replace(reg, "")
        if(val.length>4){
          val=val.substr(0,4)
        }
        this.saveDictionary.dataCode = val;
      },
      add() {
        let node = this.$refs.dictTree.getCheckedNodes();
        if (node && node.length) {
          this.saveDictionary={
            "id": 0,
            "deleted":0,//删除标记
            "dictCode":"",//字典编码
            "dataCode": "",//数据编码
            "dataText": "",//数据文本值
            "dataTextAbbr": "",//数据文本值拼音缩写
            "dataValue": "",//数据数字值
            "dataDescribe": "",//数据扩展描述
            "sort": 0,//排序
            "remark": "",//备注
            "asDefault":0,//默认值
            "disableState":0,//禁用值
            "version": 0,//版本
            "funeralParlourCode": 0,//殡仪馆代码
          };
          this.modifyFlag = false;//添加标志
          this.saveDictionary.dataDescribe = node[0].dictText
          this.saveDictionary.dictCode = node[0].id
          this.dialogVisibleType = true
        }else{
          this.$message("请选择系统字典")
        }
      },
      //明细修改
      modifyItem(id){
        let node = this.$refs.dictTree.getCheckedNodes();
        if (node && node.length) {
          let data = this.$refs.singleDictionTable.selection;
          let item = null;
          let this_modify = this;
          if (data && data.length) {
            if (data[0].unmodified==1){
              this.$message("不可修改")
              return
            }
            item = data[0];
            let postData = {
              "id": item.id
            }
            //载入字典明细
            API['loadDictionaryDataWithId'](postData).then(response => {
              let data = response;
              if (!data) {
                this.$message(data.message)
                return
              } else {
                this_modify.modifyFlag = true;
                this_modify.saveDictionary = data.data;
                this_modify.saveDictionary.dictCode = node[0].id
                this_modify.saveDictionary.dataDescribe = node[0].dictText
                this_modify.dialogVisibleType = true;
                //加载data
              }

            }).catch(error => {
              this.$message(error)
            })
          }else{
            this.$message("请选择")
          }

        }else{
          this.$message("请选择系统字典")
        }
      },
      closeDialog(){
        this.saveDictionary={};
        this.dialogVisibleType=false;
      },//根据明细id删除明细数据
      deleteItem(){
        let data= this.$refs.singleDictionTable.selection;
        let item=null;
        if(data && data.length>0){
          item=data[0];
        }else{
          this.$message("未选中")
          return ;
        }
        if (item.unmodified==1){
          this.$message("不可修改")
          return
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData=[{
            "id": item.id,
            "version":item.version
          }]
          //载入字典明细
          API['deleteDictionaryDataWithId'](postData).then(response=>{
            let data=response;
            if (!data) {
              this.$message(data.message)
              return
            }else{
              let node = this.$refs.dictTree.getCheckedNodes();
              //加载字典明细项
              this.loadDictionaryDataListWithCode(node[0].dictCode);
              this.$message(data.message)
            }
            //加载data

          }).catch(error => {
            this.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });
      } ,
      onlySortNumber(){
        // 先把非数字的都替换掉，除了数字和.
        let obj=this.saveDictionary.sort;
        obj=Number.parseInt(obj);
        this.saveDictionary.sort=obj;
      },
      //加载字典类型
      R(){
        let postData={
        }
        API['loadDictionaryList'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }

          this.treeData = treeDictionaryformate(data)

        }).catch(error => {
          this.$message(error)
        })
      },
      //根据id加载物品，服务类型详情
      loadDictionaryDataListWithCode(dictCode){
        let postData={
          "dictCode": dictCode
        }
        let this_load=this;
        // this.treeData = treeDictionaryformate(this.ceshi)
        API['loadDictionaryDataListWithCode'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this_load.$message('数据读取失败')
            return
          }
          let loadData= treeDictionaryformate(data);
          //获得第一个返回值的children
          this_load.dictionaryTableData = loadData[0].children;
        }).catch(error => {
          this_load.$message(error)
        })
      },
      //tree单选
      handleCheck(data,checked, node){
        if(checked && data.label!="系统字典") {
          this.$refs.dictTree.setCheckedNodes([data]);
          node = this.$refs.dictTree.getCheckedNodes();
          console.log(node[0].dictCode);
          this.editArr = [data.dictCode];
          let this_local = this;
          //描述
          this_local.saveDictionary.dataDescribe = data.dictText;
          //类型编码，记录字典编码code
          this_local.saveDictionary.dictCode = data.dictCode;
          //加载字典明细项
          this_local.loadDictionaryDataListWithCode(data.dictCode);
        }
      },
      //点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        if (this.tableSelection.length>0){
          this.$refs.singleDictionTable.toggleRowSelection(this.tableSelection[0],false);
        }
        this.$refs.singleDictionTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.singleDictionTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection
      },

      selectAll(selection) {
        if (selection.length >1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },
      //字典保存
      submit(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        this.$refs.dicdialog.validate(valid=>{
          if (valid) {
            let postData=this.saveDictionary;
            let this_submit=this;
            this.saveFlag = true;
            API['saveDictionaryData'](postData).then(response=>{
              if(response){
                let data=response;
                if (!data) {
                  this.saveFlag = false;
                  this.$message('数据读取失败')
                  return
                }
                this_submit.dialogVisibleType=false;
                let node = this.$refs.dictTree.getCheckedNodes();

                //加载字典明细项
                this_submit.loadDictionaryDataListWithCode(node[0].dictCode);
                console.log(this.saveDictionary)
                this.saveFlag = false;
              }else{
                this.$message('数据保存失败')
                this.saveFlag = false;
              }

            }).catch(error => {
              this.$message(error)
            })
          }
        })
      },//取消
      cancelForm(){
        this.saveDictionary={
          "id": 0,
          "deleted":0,//删除标记
          "dictCode":"",//字典编码
          "dataCode": "",//数据编码
          "dataText": "",//数据文本值
          "dataTextAbbr": "",//数据文本值拼音缩写
          "dataValue": "",//数据数字值
          "dataDescribe": "",//数据扩展描述
          "sort": 0,//排序
          "remark": "",//备注
          "asDefault":0,//默认值
          "disableState":0,//禁用值
          "version": 0,//版本
          "funeralParlourCode": 0,//殡仪馆代码
        };
        this.dialogVisibleType = false
      }

    },
    watch:{
      "dialogVisibleType"(){
        if (this.dialogVisibleType==false){
          this.$nextTick(() => {
            this.$refs.dicdialog.resetFields();
          })
        }
      }
    }
  }
</script>
<style scoped>

</style>
